package com.mimose.component.chains.entity.response;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description 链路处理返回体（异步）
 * @Author ccy
 * @Date 2019/10/30 11:37
 */
@Slf4j
public final class ResponseAsyn<B extends ResponseBaseDto> extends AbsResponse<CompletableFuture> {

    private CompletableFuture<B> task;

    @Override
    public ResponseAsyn end(boolean done, CompletableFuture data) {
        this.task = data;
        this.done = done;
        return this;
    }

    /**
     * 只允许通过该方式获取task结果
     * @param timeOut 超时时间（s）
     * @return
     */
    public B getResponse(Integer timeOut){
        if(this.task!=null && timeOut !=null && timeOut >= 0){
            try {
                return this.task.get(timeOut, TimeUnit.SECONDS);
            }catch (final TimeoutException e){
                log.error("TResponseAsyn getResponse timeout", e);
            }catch (final Exception e) {
                log.error("TResponseAsyn getResponse error", e);
            }
        }
        return null;
    }
}
